//
//  DNBaseTextField.swift
//  LunalerApp
//
//  Created by 露乐ios on 2018/2/9.
//  Copyright © 2018年 露乐ios. All rights reserved.
//

import UIKit

@objc protocol DNBaseTextFieldDelegate : NSObjectProtocol {
    
    @objc optional static func configGlobleFormatStr() -> NSString
    
    @objc optional func baseTextFiedlDidchangeText(textField:DNBaseTextField,text:NSString)
    
    @objc optional func baseTextFieldDidFinshWithNumber(textField:DNBaseTextField,number:NSString)
    
    @objc optional func baseTextFieldShouldReturn(textField:DNBaseTextField)
}

fileprivate extension Selector
{
    static let textFieldDidChange = #selector(DNBaseTextField.textFieldDidChange);
}

class DNBaseTextField: UITextField ,DNBaseTextFieldDelegate{

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */
    let UCSTextFieldSeparateCharacter = " "
    var numbers : NSString{
        get{
            return self.removeSpaceCharacter(originalString: self.text! as NSString)
        }
    }  //返回无空格的字符串
    var baseDelegate : DNBaseTextFieldDelegate?
    
    fileprivate lazy var defaultFormatStr : NSString = {
        return ""
    }()
    
    fileprivate var formatStrs : NSArray = {
        let tempArr = NSArray()
        return tempArr
    }()
    
    fileprivate var numberCount = 0
    
 
    func setBaseNumber(number:NSString) {
        
    }
    
    func setGlobleFormatStr(defaultFormatStr:NSString) {
        self.defaultFormatStr = defaultFormatStr
        self.numberCount = self.removeSpaceCharacter(originalString: self.defaultFormatStr).length
        self.p_configGlobleMes()
    }
    
    
    class func configGlobleFormatStr(formatStr:NSString){
        print("\(#function)--请不要直接在基类中调用此方法,你需要在子类中重写此方法")
    }
    

    func removeSpaceCharacter(originalString:NSString) -> NSString {
        return originalString.dnStringByReplacingOccurrencesOfStringwithString(target: UCSTextFieldSeparateCharacter, replacement: "") as! NSString
    }
    
    @objc func textFieldDidChange(noti:NSNotification){
        
    }
    
    func p_configGlobleMes(){
        let tempArr = self.defaultFormatStr.components(separatedBy: self.UCSTextFieldSeparateCharacter) as NSArray
        self.formatStrs = tempArr.copy() as! NSArray
        
        self.delegate = self as? UITextFieldDelegate
        self.keyboardType = .phonePad
        NotificationCenter.default.addObserver(self, selector: .textFieldDidChange, name: NSNotification.Name.UITextFieldTextDidChange, object: nil)
    }
    
    
    func p_adjustContent(){
        let tmpStr = self.text
        // 将类型转换为
        var countNum = 0
        self.formatStrs.enumerateObjects{ (str:Any, index:NSInteger, stop : UnsafeMutablePointer<ObjCBool>) in
            let tempStr = str as! NSString
            if tmpStr?.lengthOfBytes(using: .utf8) == countNum + tempStr.length + index * 1 && tempStr.length < self.defaultFormatStr.length{
                self.text = tmpStr?.appending(UCSTextFieldSeparateCharacter)
                countNum += 1
            }
            countNum += tempStr.length // 每次加一
        }
    }
    
    func p_appendStringWithRange(string:NSString,range:NSRange){
        let storateStr  = self.text! as NSString
        let selectedStr = storateStr.substring(with: range)
        let removeCount = self.removeSpaceCharacter(originalString: selectedStr as NSString).length // 要移除的数量
        
        let lastCount = self.numberCount - self.removeSpaceCharacter(originalString: self.text! as NSString).length + removeCount as NSInteger
        if lastCount <= 0 {
            return;
        }
        // 要粘贴字符串中非空格字符
        var strNoSpace : NSString = self.removeSpaceCharacter(originalString: string);
        
        // 设置需要的字符信息
        if strNoSpace.length > lastCount {
            strNoSpace = strNoSpace.substring(to: lastCount) as NSString
        }
        
        let newString : NSString = storateStr.replacingCharacters(in: range, with: strNoSpace as String) as NSString
        
        let newStrNoSpace = self.removeSpaceCharacter(originalString: newString)
        
        self.text = nil
        
        for i in 0...newStrNoSpace.length-1 {
            let  tempStr = newStrNoSpace;
            let  charStr = tempStr.substring(with: NSRange.init(location: i, length: 1))
            p_adjustContent()
            if (self.text?.lengthOfBytes(using: .utf8))! < self.numberCount + self.formatStrs.count - 1{
                self.text = (self.text! as NSString).appending(charStr)
                textchange()
            }
        }
    }
    
    func paste(sender : AnyObject){
        super.paste(sender)
        let noti = NSNotification.init(name: NSNotification.Name(rawValue: "pastNotification"), object: self)
        textFieldDidChange()
    }
    
    func textchange(){
        
        if (self.baseDelegate?.responds(to: #selector(DNBaseTextFieldDelegate.baseTextFiedlDidchangeText(textField:text:))))! {
            self.baseDelegate?.baseTextFiedlDidchangeText!(textField: self, text: self.numbers)
        }
    }
    
    
    deinit {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UITextFieldTextDidChange, object: nil)
    }
    
}
